package com.ruoyi.saleReturn.service.impl;

import com.ruoyi.audit.domain.Audit;
import com.ruoyi.audit.mapper.AuditMapper;
import com.ruoyi.audit.service.AuditService;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.text.Convert;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.WXShiroUtils;
import com.ruoyi.procurement.domain.ProcurementModel;
import com.ruoyi.procurement.mapper.ProcurementOrderMapper;
import com.ruoyi.product.domain.ProductModel;
import com.ruoyi.product.mapper.ProductMapper;
import com.ruoyi.purchaseReturn.domain.PurchaseReturnModel;
import com.ruoyi.purchaseReturn.domain.PurchaseReturnOrder;
import com.ruoyi.purchaseReturn.mapper.PurchaseReturnMapper;
import com.ruoyi.sale.domain.SaleGoodsModel;
import com.ruoyi.sale.domain.SaleGoodsOrder;
import com.ruoyi.sale.domain.SaleorderOrder;
import com.ruoyi.sale.mapper.SaleGoodsMapper;
import com.ruoyi.saleReturn.domain.SaleReturnModel;
import com.ruoyi.saleReturn.domain.SaleReturnOrder;
import com.ruoyi.saleReturn.mapper.SaleReturnMapper;
import com.ruoyi.saleReturn.saleReturnStatusMachine.SaleReturnService;
import com.ruoyi.saleReturn.saleReturnStatusMachine.SaleReturnServiceFactory;
import com.ruoyi.saleReturn.service.ISaleReturnService;
import com.ruoyi.warehousing.domain.Warehousing;
import com.ruoyi.warehousing.domain.WarehousingRecords;
import com.ruoyi.warehousing.mapper.WarehousingMapper;
import com.ruoyi.warehousing.mapper.WarehousingRecordsMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.parameters.P;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 【请填写功能名称】Service业务层处理
 *
 * @author jndj
 * @date 2022-06-17
 */
@Service
public class SaleReturnServiceImpl implements ISaleReturnService {

    @Autowired
    private SaleReturnMapper saleReturnMapper;

    @Autowired
    private AuditMapper auditMapper;

    @Autowired
    private SaleGoodsMapper saleGoodsMapper;

    @Autowired
    private PurchaseReturnMapper purchaseReturnMapper;

    @Autowired
    private WarehousingMapper warehousingMapper;

    @Autowired
    private ProcurementOrderMapper procurementOrderMapper;

    @Autowired
    private WarehousingRecordsMapper warehousingRecordsMapper;

    @Autowired
    private ProductMapper productMapper;

    @Override
    public SaleReturnOrder selectSaleReturnOrderById(Long saleReturnModelId) {
        return saleReturnMapper.selectSaleReturnOrderById(saleReturnModelId);
    }

    @Override
    public List<SaleReturnOrder> selectSaleReturnOrderList(SaleReturnOrder nytSaleReturnOrder) {
        return saleReturnMapper.selectSaleReturnOrderList(nytSaleReturnOrder);
    }

    @Override
    public int insertSaleReturnOrder(SaleReturnOrder nytSaleReturnOrder) {
        return saleReturnMapper.insertSaleReturnOrder(nytSaleReturnOrder);
    }

    @Override
    public int updateSaleReturnOrder(SaleReturnOrder nytSaleReturnOrder) {
        return saleReturnMapper.updateSaleReturnOrder(nytSaleReturnOrder);
    }

    @Override
    public int deleteSaleReturnOrderByIds(String ids) {
        return saleReturnMapper.deleteSaleReturnOrderByIds(Convert.toStrArray(ids));
    }

    @Transactional
    @Override
    public int deleteSaleReturnOrderById(Long saleReturnId) {
        SaleReturnOrder saleReturnOrder = saleReturnMapper.selectSaleReturnOrderAndModelById(saleReturnId);
        //删除 采购退货单 主表和子表信息
        int a = saleReturnMapper.deleteSaleReturnOrderById(saleReturnId);
        if (saleReturnOrder.getSaleReturnModels() != null) {
            for (SaleReturnModel saleReturnModel : saleReturnOrder.getSaleReturnModels()) {
                int b = saleReturnMapper.deleteSaleReturnModelById(saleReturnModel.getSaleReturnModelId());
            }
        }

        //删除 审核表 信息
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("orderId", saleReturnId);
        hashMap.put("orderType", "6");
        int c = auditMapper.deleteAuditWith(hashMap);
        //修改  istrue 状态
        //先判断 是选择的那个类型单子
        HashMap hashMapa = new HashMap();
        if (saleReturnOrder.getSaleGoodsId() != null) {
            List<SaleGoodsModel> saleGoodsModelList = new ArrayList<>();
            SaleGoodsModel saleGoodsModel = new SaleGoodsModel();
            int count = 0;
            for (SaleReturnModel saleReturnModel : saleReturnOrder.getSaleReturnModels()) {
                saleGoodsModel = saleGoodsMapper.selectSalegoodsModelReturn(saleReturnModel.getSaleGoodsModelId());
                saleGoodsModel.setRemainingNum(saleGoodsModel.getRemainingNum() + saleReturnModel.getAllNum());
                saleGoodsMapper.updateSaleGoodsModel(saleGoodsModel);
                saleGoodsModelList.add(saleGoodsModel);
            }
            for (SaleGoodsModel saleGoodsModel1 : saleGoodsModelList) {
                count += saleGoodsModel1.getRemainingNum();
            }
            if (count != 0) {
                hashMapa.put("status", 0);
                hashMapa.put("saleGoodsId", saleReturnOrder.getSaleGoodsId());
                saleGoodsMapper.updateSaleGoodsStatus(hashMapa);
            }

        } else {
            PurchaseReturnModel purchaseReturnModel = new PurchaseReturnModel();
            List<PurchaseReturnModel> purchaseReturnModelList = new ArrayList<>();
            int count = 0;
            for (SaleReturnModel saleReturnModel : saleReturnOrder.getSaleReturnModels()) {
                purchaseReturnModel = purchaseReturnMapper.selectPurchaseReturnModelById(saleReturnModel.getPurchaseReturnModelId());
                purchaseReturnModel.setRemainingNum(purchaseReturnModel.getRemainingNum() + saleReturnModel.getAllNum());
                purchaseReturnMapper.updatePurchaseReturnModel(purchaseReturnModel);
                purchaseReturnModelList.add(purchaseReturnModel);
            }

            for (PurchaseReturnModel purchaseReturnModel1 : purchaseReturnModelList) {
                count += purchaseReturnModel1.getAllNum();

            }
            if (count != 0) {
                //改变采购退货的状态
                HashMap hashMapb = new HashMap();
                hashMapb.put("status", 0);
                hashMapb.put("purchaseReturnId", saleReturnOrder.getPurchaseReturnId());
                purchaseReturnMapper.updatePurchaseReturnStatus(hashMapb);
            }

        }
        if (a > 0 && c > 0) {
            return 1;
        } else {
            return 0;
        }
    }

    @Override
    public List<SaleGoodsModel> selectShowSaleGoodsModelById(Long saleGoodsId) {
        return saleReturnMapper.selectShowSaleGoodsModelById(saleGoodsId);
    }

    @Override
    public SaleGoodsModel selectSaleGoodsModel(HashMap<Object, Object> hashMap) {
        return saleReturnMapper.selectSaleGoodsModel(hashMap);
    }

    @Override
    public List<PurchaseReturnOrder> selectPurchaseReturnList(PurchaseReturnOrder purchaseReturnOrder) {
        return saleReturnMapper.selectPurchaseReturnList(purchaseReturnOrder);
    }

    @Override
    public List<PurchaseReturnModel> selectShowPurchaseReturnModelById(Long purchaseReturnId) {
        return saleReturnMapper.selectShowPurchaseReturnModelById(purchaseReturnId);
    }

    @Override
    public int insertSaleReturnModel(SaleReturnModel saleReturnModel) {
        return saleReturnMapper.insertSaleReturnModel(saleReturnModel);
    }

    /**
     * 销售退货 增加库存
     *
     * @param saleReturnId 销售退货单id
     * @param status       销售退货单审核状态
     */
    @Override
    public void saleReturnAudit(Long saleReturnId, String status) {
        //根据主键查询数据，判断是否含有产品规格型号子集
        SaleReturnOrder saleReturnOrder = saleReturnMapper.selectSaleReturnOrderAndModelById(saleReturnId);
        //如果驳回 修改订单状态
        if ("2".equals(status)) {
            saleReturnOrder.setAuditTime(DateUtils.getNowDate());
            saleReturnMapper.updateSaleReturnOrder(saleReturnOrder);
            if (saleReturnOrder.getSaleGoodsId() != null) {
                SaleGoodsModel saleGoodsModel = new SaleGoodsModel();
                for (SaleReturnModel saleReturnModel : saleReturnOrder.getSaleReturnModels()) {
                    saleGoodsModel = saleGoodsMapper.selectSalegoodsModelReturn(saleReturnModel.getSaleGoodsModelId());
                    saleGoodsModel.setRemainingNum(saleGoodsModel.getRemainingNum() + saleReturnModel.getAllNum());
                    saleGoodsMapper.updateSaleGoodsModel(saleGoodsModel);

                }
                //选择的 销货单退货
                SaleGoodsOrder saleGoodsOrder = new SaleGoodsOrder();
                saleGoodsOrder.setSaleGoodsId(saleReturnOrder.getSaleGoodsId());
                saleGoodsOrder.setIsReturn("0");
                saleGoodsMapper.updateSaleGoodsOrder(saleGoodsOrder);
            } else {
                PurchaseReturnModel purchaseReturnModel;
                for (SaleReturnModel saleReturnModel : saleReturnOrder.getSaleReturnModels()) {
                    purchaseReturnModel = purchaseReturnMapper.selectPurchaseReturnModelById(saleReturnModel.getPurchaseReturnModelId());
                    purchaseReturnModel.setRemainingNum(purchaseReturnModel.getRemainingNum() + saleReturnModel.getAllNum());
                    purchaseReturnMapper.updatePurchaseReturnModel(purchaseReturnModel);

                }
                //选择的是 采购退货单退货
                PurchaseReturnOrder purchaseReturnOrder = new PurchaseReturnOrder();
                purchaseReturnOrder.setPurchaseReturnId(saleReturnOrder.getPurchaseReturnId());
                purchaseReturnOrder.setIsReturn("0");
                purchaseReturnMapper.updatePurchaseReturn(purchaseReturnOrder);
            }
        } else {
            if (saleReturnOrder.getSaleReturnModels() != null) {
                //循环插入库存数据
                List<SaleReturnModel> saleReturnModels = saleReturnOrder.getSaleReturnModels();
                WarehousingRecords warehousingRecords = new WarehousingRecords();
                for (SaleReturnModel saleReturnModel : saleReturnModels) {
                    int num = saleReturnModel.getAllNum();
                    int returnNum1 = saleReturnModel.getReturnNum();
                    //找库存表 采购退货扣减库存
                    Warehousing warehousing = new Warehousing();
                    warehousing.setDeptId(saleReturnOrder.getDeptId());
                    //有两种情况 一种是选择采购退货单 一种是 选择的销货单
                    Warehousing warehousing1;
                    if (saleReturnOrder.getSaleGoodsId() != null) {
                        long salemodelId = saleReturnModel.getSaleGoodsModelId();
                        HashMap map = new HashMap();
                        map.put("backnum", num);
                        map.put("sale_goods_model_id", salemodelId);
                        saleGoodsMapper.updateBackNum(map);
                        //根据退货单从表的 销货单从表id sale_goods_model_id找 原来单子 的数据
                        SaleGoodsModel saleGoodsModel = saleGoodsMapper.selectSaleGoodsModelByModelId(saleReturnModel.getSaleGoodsModelId());
                        saleGoodsModel.setBacknum(num);
                        warehousing.setProductId(saleGoodsModel.getSelectId());
                        warehousing.setSelectId(saleGoodsModel.getSelectId());
                        warehousing.setProductType(saleGoodsModel.getProductType());
                        warehousing.setBatch(saleGoodsModel.getBatch());
                        warehousing.setDeptId(SecurityUtils.getLoginUser().getCompanyId());
                        warehousing1 = warehousingMapper.selectWarehousing(warehousing);
                        saleGoodsModel.setRemainingNum(saleGoodsModel.getRemainingNum() - num);
                        // saleGoodsModel.setRemainingNum(saleGoodsModel.getRemainingNum() - returnNum1);
                        //      saleGoodsMapper.updateSaleGoodsModel(saleGoodsModel);
                    } else {
                        //根据退货单从表的 采购退货单从表id purchase_return_model_id找 原来单子 的数据
                        PurchaseReturnModel purchaseReturnModel = purchaseReturnMapper.selectPurchaseReturnModelById(saleReturnModel.getPurchaseReturnModelId());
                        //采购退货单 存的 采购出库单 从表的id
                        ProcurementModel procurementModel = purchaseReturnMapper.selectProcurementModelByNo(purchaseReturnModel.getProcurementWarehousingNo());
                        //因为这里的采购退货单 是对方公司做的单子 产品的id也是对方的 这里要把id换成 自己公司的
                        //ProductModel productModel = productMapper.selectProductByModelCode(ShiroUtils.getSysUser().getCompanyId(), procurementModel.getModelCode());
                        ProductModel productModel = productMapper.selectProductByModelCode(SecurityUtils.getLoginUser().getCompanyId(), procurementModel.getModelCode());
                        warehousing.setProductId(productModel.getProductId());
                        warehousing.setProductType(procurementModel.getProductType());
                        warehousing.setBatch(procurementModel.getBatch());
                        warehousing.setSelectId(procurementModel.getProductId());
                        warehousing.setDeptId(SecurityUtils.getLoginUser().getCompanyId());
                        warehousing1 = warehousingMapper.selectWarehousing(warehousing);
                    }
                    //存储本次增加的数量
                    int returnNum = saleReturnModel.getReturnNum();
                    warehousingRecords.setInventoryNum(returnNum1);
                    warehousingRecords.setAllnum(num);
                    //判断是否拥有该公司该产品该型号名称的库存记录
                    if (warehousing1 == null) {
                        warehousingMapper.insertWarehousing(warehousing);
                    } else {
                        Long warehousingNum = warehousing1.getAmount();
                        Long num1 = Long.valueOf(num);
                        num1 = warehousingNum + num;
                        warehousing.setAmount(num1);
                        warehousing.setWarehousingId(warehousing1.getWarehousingId());
                        warehousingMapper.updateWarehousing(warehousing);
                    }
                    Long warehousingId = warehousing.getWarehousingId();
                    warehousingRecords.setWarehousingId(warehousingId);
                    warehousingRecords.setSupplierId(saleReturnOrder.getCompanyId());
                    //销售退货为6
                    warehousingRecords.setInventoryStatus("6");
                    warehousingRecords.setCreateBy(SecurityUtils.getLoginUser().getUser().getUserName());
                    warehousingRecordsMapper.insertWarehousingRecords(warehousingRecords);

                    //通过后更新状态
                    SaleReturnOrder saleReturnOrder2 = new SaleReturnOrder();
                    saleReturnOrder2.setSaleReturnId(saleReturnOrder.getSaleReturnId());
                    saleReturnOrder2.setSaleReturnStatus(status);
                    saleReturnMapper.updateSaleReturnOrder(saleReturnOrder2);
                }
            }
        }
    }

    @Override
    public SaleReturnOrder selectSaleReturnOrderAndModelById(Long purchaseReturnId) {
        return saleReturnMapper.selectSaleReturnOrderAndModelById(purchaseReturnId);
    }

    @Override
    public List<SaleReturnOrder> selectSaleReturnOrderListCustObj(Long companyId) {
        return saleReturnMapper.selectSaleReturnOrderListCustObj(companyId);
    }

    @Override
    public List<SaleorderOrder> selectPurchaseReturnCustObj(Long companyId) {
        return saleReturnMapper.selectPurchaseReturnCustObj(companyId);
    }

    private AuditService auditService;

    public SaleReturnServiceImpl(AuditService auditService) {
        this.auditService = auditService;
    }


    @Autowired
    private SaleReturnServiceFactory factory;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int auditSale(Long saleReturnId, String status) {

        // 封装数据
        SaleReturnOrder saleReturnOrder = new SaleReturnOrder();
        // 订单ID
        saleReturnOrder.setSaleReturnId(saleReturnId);
        // 订单状态
        saleReturnOrder.setSaleReturnStatus(status);
        // 订单审核时间
        saleReturnOrder.setAuditTime(new Date());

        // 修改当前订单
        saleReturnMapper.updateSaleReturnOrder( saleReturnOrder);

        // 获取工厂实例
        SaleReturnService impl = factory.getImpl(status);
        // 操作库存
        return impl.execute(saleReturnOrder);
    }


    @Override
    public Long querypreviousId(Long saleReturnId) {
        Map<String, Object> params = new HashMap<>();
        params.put("saleReturnId", saleReturnId);
        params.put("deptId", SecurityUtils.getDeptId());
        return saleReturnMapper.querypreviousId(params);
    }

    @Override
    public Long queryNextId(Long saleReturnId) {
        Map<String, Object> params = new HashMap<>();
        params.put("saleReturnId", saleReturnId);
        params.put("deptId", SecurityUtils.getDeptId());
        return saleReturnMapper.queryNextId(params);
    }

    @Override
    public List<Map<String, Object>> pendingReview(Long deptID) {
        return saleReturnMapper.pendingReview(deptID)
                .stream()
                .peek(item -> item.put("orderType", "销售退货"))
                .collect(Collectors.toList());
    }
}
